package com.zhilehuo.pretask.repo

import com.zhilehuo.pretask.poko.ArticleDetail
import com.zhilehuo.pretask.poko.ArticleDetailResponse
import okhttp3.OkHttpClient
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * @Description: 单文章内容仓库类
 * @Author: Realnt
 * @Date:
 */
class ArticleRepository {
    /**
     * @Description: 文章请求接口
     * @Author: Realnt
     * @Date:
     */
    interface ArticleService {
        @GET("knowledge/article/getArticleDetail")
        suspend fun getArticleDetail(
            @Query("aid") aid: Int,
            @Header("Cookie") cookie: String = "sid=i5VMMK2c7EEm5qK597kJeDqrel7NKCRqSQRGQn8mJBs=",
            @Header("Vary") vary: String = "Accept-Encoding",
            @Header("Content-Encoding") contentEncode: String = "gzip"
        ): Response<ArticleDetailResponse>
    }

    /**
     * @Description: Retrofit实例, 默认单例
     * @Author: Realnt
     * @Date:
     */
    object RetrofitClient {
        private const val BASE_URL = "https://shiqu.zhilehuo.com/"

        val service: ArticleService by lazy {
            Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(getUnsafeOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ArticleService::class.java)
        }

        /**
         * @Description: 创建不安全信任管理器(测试用)
         * @Param  :
         * @Return OkHttpClient : 返回一个信任所有SSL证书的OkHttpClient
         */
        fun getUnsafeOkHttpClient(): OkHttpClient {
            val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
                override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
            })

            val sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())

            return OkHttpClient.Builder()
                .sslSocketFactory(sslContext.socketFactory, trustAllCerts[0] as X509TrustManager)
                .hostnameVerifier { _, _ -> true }
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build()
        }
    }

    /**
     * @Description: 获取文章详情
     * @Param aid : 文章编号
     * @Return Result<ArticleDetail> : 接口返回值, 含标记和请求数据
     */
    suspend fun getArticleDetail(aid: Int): Result<ArticleDetail> {
        return try {
            val apiService = RetrofitClient.service
            val response = apiService.getArticleDetail(aid)
            if (response.isSuccessful) {
                Result.success(response.body()?.data ?: throw Exception("空的response"))
            } else {
                Result.failure(Exception("HTTP错误: ${response.code()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}